<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入商品标题" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <TreeSelect
          v-model:value="queryParams.categoryId"
          :options="categoryTree"
          :objMap="{ value: 'categoryId', label: 'name', children: 'children' }"
          placeholder="选择分类"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="queryParams.supplierId" placeholder="选择供应商" clearable style="width: 240px">
          <el-option v-for="item in supplierOptions" :key="item.supplierId" :label="item.name" :value="item.supplierId" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 240px">
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['ug:goods:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['ug:goods:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['ug:goods:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" align="center" prop="goodsId" width="80" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="分类ID" align="center" prop="categoryId" width="100" />
      <el-table-column label="供应商ID" align="center" prop="supplierId" width="110" />
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="审核" align="center" prop="auditStatus" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.auditStatus === 0" type="warning">待审</el-tag>
          <el-tag v-else-if="scope.row.auditStatus === 1" type="success">通过</el-tag>
          <el-tag v-else-if="scope.row.auditStatus === 2" type="danger">驳回</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="销量" align="center" prop="sales" width="100" />
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ug:goods:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ug:goods:remove']"></el-button>
          </el-tooltip>
          <el-tooltip content="审核通过" placement="top">
            <el-button link type="success" icon="Check" @click="handleAudit(scope.row, 1)" v-hasPermi="['ug:goods:audit']"></el-button>
          </el-tooltip>
          <el-tooltip content="审核驳回" placement="top">
            <el-button link type="danger" icon="Close" @click="handleAudit(scope.row, 2)" v-hasPermi="['ug:goods:audit']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="分类" prop="categoryId">
          <TreeSelect
            v-model:value="form.categoryId"
            :options="categoryTree"
            :objMap="{ value: 'categoryId', label: 'name', children: 'children' }"
            placeholder="选择分类"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="form.supplierId" placeholder="选择供应商" filterable style="width: 100%">
            <el-option v-for="item in supplierOptions" :key="item.supplierId" :label="item.name" :value="item.supplierId" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" maxlength="120" />
        </el-form-item>
        <el-form-item label="副标题" prop="subtitle">
          <el-input v-model="form.subtitle" placeholder="副标题" maxlength="255" />
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <ImageUpload v-model="form.cover" :limit="1" :isShowTip="false" />
        </el-form-item>
        <el-form-item label="详情" prop="descHtml">
          <Editor v-model="form.descHtml" :minHeight="200" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-divider content-position="left">SKU 管理</el-divider>
        <div v-if="!form.goodsId" class="sku-tip">
          <el-alert type="info" show-icon :closable="false" title="请先保存商品基本信息，保存后可管理 SKU" />
        </div>
        <div v-else>
          <div class="mb8">
            <el-button type="primary" plain icon="Plus" @click="openAddSku">新增 SKU</el-button>
            <el-button type="danger" plain icon="Delete" :disabled="skuMultiple" @click="removeSkuBatch">删除所选</el-button>
            <el-button plain icon="Refresh" @click="loadSkus">刷新</el-button>
          </div>
          <el-table v-loading="skuLoading" :data="skuList" @selection-change="handleSkuSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="SKUID" prop="skuId" width="90" align="center" />
            <el-table-column label="价格" prop="price" width="120" />
            <el-table-column label="划线价" prop="originPrice" width="120" />
            <el-table-column label="库存" prop="stock" width="100" />
            <el-table-column label="条码" prop="barcode" />
            <el-table-column label="状态" prop="status" width="120">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
                <el-tag v-else type="info">禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="编辑" placement="top">
                  <el-button link type="primary" icon="Edit" @click="openEditSku(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="danger" icon="Delete" @click="removeSku(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="库存变更" placement="top">
                  <el-button link type="warning" icon="RefreshRight" @click="openChangeStock(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- SKU 编辑弹窗 -->
    <el-dialog :title="skuTitle" v-model="skuOpen" width="500px" append-to-body>
      <el-form :model="skuForm" :rules="skuRules" ref="skuFormRef" label-width="100px">
        <el-form-item label="价格" prop="price">
          <el-input v-model="skuForm.price" placeholder="如 9.90" />
        </el-form-item>
        <el-form-item label="划线价" prop="originPrice">
          <el-input v-model="skuForm.originPrice" placeholder="可选" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="skuForm.stock" :min="0" :step="1" />
        </el-form-item>
        <el-form-item label="条码" prop="barcode">
          <el-input v-model="skuForm.barcode" placeholder="可选" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="skuForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSku">保 存</el-button>
          <el-button @click="skuOpen=false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 库存变更弹窗 -->
    <el-dialog title="库存变更" v-model="stockOpen" width="450px" append-to-body>
      <el-form :model="stockForm" ref="stockFormRef" label-width="100px">
        <el-form-item label="SKUID">
          <el-input v-model="stockForm.skuId" disabled />
        </el-form-item>
        <el-form-item label="变动数量">
          <el-input-number v-model="stockForm.change" :min="-999999" :max="999999" :step="1" />
        </el-form-item>
        <el-form-item label="业务类型">
          <el-select v-model="stockForm.bizType" style="width: 100%">
            <el-option label="手工调整" value="manual" />
            <el-option label="下单" value="order" />
            <el-option label="退款" value="refund" />
          </el-select>
        </el-form-item>
        <el-form-item label="业务单号">
          <el-input v-model="stockForm.bizNo" placeholder="可选" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="stockForm.remark" type="textarea" :rows="2" placeholder="可选" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitChangeStock">确 定</el-button>
          <el-button @click="stockOpen=false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import { listGoods, addGoods, updateGoods, delGoods, getGoods, changeGoodsStatus, changeGoodsAudit, listSkuByGoods, addSku, updateSku, delSku, changeSkuStock } from '@/api/ug/goods'
import { listSupplier } from '@/api/ug/supplier'
import { listCategory } from '@/api/ug/category'
import ImageUpload from '@/components/ImageUpload'
import Editor from '@/components/Editor'
import TreeSelect from '@/components/TreeSelect'

const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict('sys_normal_disable')

const list = ref([])
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const open = ref(false)
const supplierOptions = ref([])
const categoryOptions = ref([])
const categoryTree = ref([])

const data = reactive({
  form: {
    goodsId: undefined,
    categoryId: undefined,
    supplierId: undefined,
    title: '',
    subtitle: '',
    cover: '',
    descHtml: '',
    status: 1,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    categoryId: undefined,
    supplierId: undefined,
    status: undefined,
  },
  rules: {
    categoryId: [{ required: true, message: '分类不能为空', trigger: 'change' }],
    supplierId: [{ required: true, message: '供应商不能为空', trigger: 'change' }],
    title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  },
  // SKU 相关表单与校验
  skuForm: {
    skuId: undefined,
    goodsId: undefined,
    price: '',
    originPrice: '',
    stock: 0,
    barcode: '',
    status: 1,
  },
  skuRules: {
    price: [{ required: true, message: '价格不能为空', trigger: 'blur' }],
  },
})

const { queryParams, form, rules } = toRefs(data)
// SKU 状态
const skuList = ref([])
const skuLoading = ref(false)
const skuIds = ref([])
const skuMultiple = ref(true)
const skuOpen = ref(false)
const skuTitle = ref('')
const skuForm = ref(data.skuForm)
const skuRules = ref(data.skuRules)

// 库存弹窗
const stockOpen = ref(false)
const stockForm = ref({ skuId: undefined, change: 0, bizType: 'manual', bizNo: '', remark: '' })

function getList() {
  loading.value = true
  listGoods(queryParams.value).then((res) => {
    loading.value = false
    list.value = res.data.list
    total.value = res.data.total
  })
}

function loadSupplierOptions() {
  // 取较大 pageSize 以获取完整下拉
  return listSupplier({ pageNum: 1, pageSize: 1000 }).then((res) => {
    supplierOptions.value = res.data.list || []
  })
}

function loadCategoryOptions() {
  return listCategory({ pageNum: 1, pageSize: 1000, status: 1 }).then((res) => {
    const flat = res.data.list || []
    categoryOptions.value = flat
    categoryTree.value = buildTree(flat)
  })
}

function buildTree(list) {
  const map = {}
  const roots = []
  list.forEach((i) => {
    map[i.categoryId] = { ...i, children: [] }
  })
  list.forEach((i) => {
    const node = map[i.categoryId]
    if (i.parentId && i.parentId !== 0 && map[i.parentId]) {
      map[i.parentId].children.push(node)
    } else {
      roots.push(node)
    }
  })
  return roots
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.goodsId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

function handleAdd() {
  resetForm()
  open.value = true
  title.value = '新增商品'
}

function handleUpdate(row) {
  resetForm()
  const id = row.goodsId || ids.value[0]
  getGoods(id).then((res) => {
    Object.assign(form.value, res.data || {})
    open.value = true
    title.value = '修改商品'
    loadSkus()
  })
}

function submitForm() {
  proxy.$refs['formRef'].validate((valid) => {
    if (!valid) return
    if (form.value.goodsId) {
      updateGoods(form.value).then(() => {
        proxy.$modal.msgSuccess('修改成功')
        open.value = false
        getList()
      })
    } else {
      addGoods(form.value).then(() => {
        proxy.$modal.msgSuccess('新增成功')
        open.value = false
        getList()
      })
    }
  })
}

function handleDelete(row) {
  const gids = row.goodsId ? row.goodsId : ids.value
  proxy.$modal
    .confirm('是否确认删除商品编号为"' + gids + '"的数据项？')
    .then(() => delGoods(gids))
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

function handleStatusChange(row) {
  const text = row.status === 1 ? '上架' : '下架'
  changeGoodsStatus(row.goodsId, row.status)
    .then(() => proxy.$modal.msgSuccess(text + '成功'))
    .catch(() => {
      row.status = row.status === 1 ? 0 : 1
    })
}

function handleAudit(row, auditStatus) {
  const text = auditStatus === 1 ? '审核通过' : '审核驳回'
  changeGoodsAudit(row.goodsId, auditStatus)
    .then(() => {
      proxy.$modal.msgSuccess(text + '成功')
      row.auditStatus = auditStatus
    })
}

function resetForm() {
  data.form = {
    goodsId: undefined,
    categoryId: undefined,
    supplierId: undefined,
    title: '',
    subtitle: '',
    cover: '',
    descHtml: '',
    status: 1,
  }
  proxy.resetForm('formRef')
}

// ============ SKU 相关 ============
function loadSkus() {
  if (!form.value.goodsId) return
  skuLoading.value = true
  listSkuByGoods(form.value.goodsId)
    .then((res) => {
      skuList.value = res.data || []
    })
    .finally(() => (skuLoading.value = false))
}

function handleSkuSelectionChange(selection) {
  skuIds.value = selection.map((i) => i.skuId)
  skuMultiple.value = !selection.length
}

function openAddSku() {
  skuTitle.value = '新增 SKU'
  skuForm.value = {
    skuId: undefined,
    goodsId: form.value.goodsId,
    price: '',
    originPrice: '',
    stock: 0,
    barcode: '',
    status: 1,
  }
  skuOpen.value = true
}

function openEditSku(row) {
  skuTitle.value = '编辑 SKU'
  skuForm.value = { ...row }
  skuOpen.value = true
}

function submitSku() {
  proxy.$refs['skuFormRef'].validate((valid) => {
    if (!valid) return
    const payload = { ...skuForm.value }
    if (payload.skuId) {
      updateSku(payload.skuId, payload).then(() => {
        proxy.$modal.msgSuccess('保存成功')
        skuOpen.value = false
        loadSkus()
      })
    } else {
      addSku(form.value.goodsId, payload).then(() => {
        proxy.$modal.msgSuccess('新增成功')
        skuOpen.value = false
        loadSkus()
      })
    }
  })
}

function removeSku(row) {
  const rmIds = row?.skuId ? row.skuId : skuIds.value
  proxy.$modal
    .confirm('确认删除 SKU：' + rmIds + '？')
    .then(() => delSku(rmIds))
    .then(() => {
      proxy.$modal.msgSuccess('删除成功')
      loadSkus()
    })
    .catch(() => {})
}

function removeSkuBatch() {
  if (!skuIds.value.length) return
  removeSku()
}

function openChangeStock(row) {
  stockForm.value = { skuId: row.skuId, change: 0, bizType: 'manual', bizNo: '', remark: '' }
  stockOpen.value = true
}

function submitChangeStock() {
  const f = stockForm.value
  if (!f.skuId || !f.change) {
    return proxy.$modal.msgError('请完善变更信息')
  }
  changeSkuStock(f).then(() => {
    proxy.$modal.msgSuccess('库存变更成功')
    stockOpen.value = false
    loadSkus()
  })
}

getList()
loadSupplierOptions()
loadCategoryOptions()
</script>

<style scoped>
</style>
